package com.nondo.rdp.finance.endpoint.api.admin;

import com.nondo.rdp.auth.common.RoleUtils;
import com.nondo.rdp.auth.common.UserUtils;
import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.endpoint.model.ConvertCall;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.auth.endpoint.model.Query;
import com.nondo.rdp.auth.service.UserService;
import com.nondo.rdp.core.common.BeanUtils;
import com.nondo.rdp.core.common.ValidateUtil;
import com.nondo.rdp.core.domain.attach.Attach;
import com.nondo.rdp.core.model.View;
import com.nondo.rdp.finance.domain.circle.Circle;
import com.nondo.rdp.finance.domain.circle.CircleComment;
import com.nondo.rdp.finance.domain.circle.CircleUp;
import com.nondo.rdp.finance.model.circle.CircleBean;
import com.nondo.rdp.finance.model.circle.CircleCommentBean;
import com.nondo.rdp.finance.model.circle.CircleQuery;
import com.nondo.rdp.finance.service.AttachService;
import com.nondo.rdp.finance.service.circle.CircleCommentService;
import com.nondo.rdp.finance.service.circle.CircleService;
import com.nondo.rdp.finance.service.circle.CircleUpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;


/**
 * 圈子
 */
@RestController("apiAdminCircle")
@RequestMapping("/api/admin/circle")
public class CircleEndpoint {
    @Autowired
    CircleService circleService;

    @Autowired
    UserService userService;

    @Autowired
    CircleCommentService circleCommentService;

    @Autowired
    CircleUpService circleUpService;

    @Autowired
    AttachService attachService;

    /**
     * 获取说说详情
     *
     * @param request
     * @param response
     * @param id
     * @return
     */
    @RequestMapping("/info/{id}")
    public View<CircleQuery> info(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        View<CircleQuery> view = new View<CircleQuery>(20000, "获取数据成功");

        Circle circleDb = null;
        CircleQuery cq = null;
        if (id != null) {
            circleDb = circleService.findOne(id);
            if (circleDb == null) {
                return View.ofError("您查看的说说不存在");
            }
            cq = this.circleService.getCircleDetail(circleDb);
        } else {
            cq = new CircleQuery();
        }

        view.setData(cq);
        return view;
    }

    /**
     * 获取说说列表
     *
     * @param request
     * @param response
     * @param query
     * @return
     */
    @RequestMapping("/list")
    public View<Page<CircleQuery>> list(HttpServletRequest request, HttpServletResponse response, @RequestBody Query<CircleBean> query) {
        View<Page<CircleQuery>> view = new View<Page<CircleQuery>>(20000, "获取列表成功");

        CircleBean circleBean = query.getData();

        Page<Circle> page = circleService.findAll(new Page<Circle>(query.getPage(), query.getSize()), circleBean);

        Page<CircleQuery> resultPage = page.convertPage(new ConvertCall<Circle, Page<CircleQuery>>() {

            @Override
            public Page<CircleQuery> execute(Page<Circle> srcPage) {

                Page<CircleQuery> circleQueryPage = new Page<CircleQuery>(srcPage.getPageNumber(), srcPage.getPageSize(), srcPage.getTotalPages(), srcPage.getTotalElements());

                List<CircleQuery> cqList = new ArrayList<CircleQuery>();

                List<Circle> cricleList = srcPage.getContent();

                for (Circle circleDb : cricleList) {
                    CircleQuery cq = circleService.getCircleDetail(circleDb);
                    cqList.add(cq);
                }
                circleQueryPage.setContent(cqList);
                return circleQueryPage;
            }

        });

        view.setData(resultPage);

        return view;
    }

    /**
     * 添加说说
     *
     * @param request
     * @param response
     * @param circle
     * @param result
     * @return
     */
    @RequestMapping("/add")
    public View<CircleBean> add(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody CircleBean circle, BindingResult result) {
        View<CircleBean> view = new View<CircleBean>(20000, "添加成功");

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
            User user = UserUtils.getUser(request, response);
            Circle circleDb = new Circle();
            BeanUtils.copy(circle, circleDb);
            circleDb.setUser(user);
            String imagePathStr = circle.getImagePaths();
            if (StringUtils.isNotBlank(imagePathStr)) {
                List<Attach> attachList = new ArrayList<Attach>();
                String[] imagePaths = imagePathStr.split(",");
                for (String imagePath : imagePaths) {
                    Attach attach = new Attach();
                    attach.setPath(imagePath);
                    attach.setRemark("说说");
                    attach.setType(0);
                    attachService.save(attach);
                    attachList.add(attach);
                    circleDb.setAttachList(attachList);
                }
            }
            this.circleService.save(circleDb);
            CircleBean circleBean = CircleBean.covert2Bean(circleDb);
            view.setData(circleBean);
        }
        return view;
    }

    /**
     * 更新说说内容
     *
     * @param request
     * @param response
     * @param circle
     * @param result
     * @return
     */
    @RequestMapping("/update")
    public View<CircleBean> update(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody CircleBean circle, BindingResult result) {
        View<CircleBean> view = new View<>(20000, "更新成功");

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
            Circle circleDb = this.circleService.findOne(circle.getId());
            circleDb.setBody(circle.getBody());
            this.circleService.update(circleDb);
        }

        return view;
    }

    /**
     * 删除说说
     *
     * @param request
     * @param response
     * @param id
     * @return
     */
    @PreAuthorize("hasRole('ROLE_" + RoleUtils.ADMIN + "')")
    @RequestMapping("/delete/{id}")
    public View delete(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        View view = new View(20000, "删除成功");

        this.circleService.delete(id);

        return view;
    }

    /**
     * 评论说说
     *
     * @param request
     * @param response
     * @param circleCommentBean
     * @param result
     * @return
     */
    @RequestMapping("/comment")
    public View<CircleQuery> comment(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody CircleCommentBean circleCommentBean, BindingResult result) {
        View<CircleQuery> view = new View<CircleQuery>(20000, "评论成功");

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
            User user = UserUtils.getUser(request, response);
            Circle circle = this.circleService.findOne(circleCommentBean.getCircleId());
            if (circle == null) {
                view.setCode(40000);
                view.setMessage("评论的说说不存在");
                return view;
            }
            CircleComment circleComment = new CircleComment();
            BeanUtils.copy(circleCommentBean, circleComment);
            circleComment.setUser(user);
            circleComment.setCircle(circle);
            circleComment.setToUser(circle.getUser());
            this.circleCommentService.save(circleComment);
            CircleQuery cq = this.circleService.getCircleDetail(circle);
            view.setData(cq);
        }

        return view;
    }

    /**
     * 删除说说回复
     *
     * @param request
     * @param response
     * @param id
     * @return
     */
    @RequestMapping("/comment/delete/{id}")
    public View commentDelete(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        View view = new View(20000, "删除成功");

        this.circleCommentService.delete(id);

        return view;
    }

    /**
     * 说说点赞和取消
     *
     * @param request
     * @param response
     * @param id
     * @return
     */
    @RequestMapping("/up/{id}")
    public View<CircleQuery> up(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        View<CircleQuery> view = new View<CircleQuery>(20000, "点赞成功");

        // 检查该用户是否已经点过赞了
        User user = UserUtils.getUser(request, response);
        Circle circle = this.circleService.findOne(id);

        CircleUp circleUp = this.circleUpService.check(circle.getId(), user.getId());
        if (circleUp == null) {
            circleUp = new CircleUp();
            circleUp.setCircle(circle);
            circleUp.setUser(user);
            this.circleUpService.save(circleUp);
        } else {
            view.setCode(20000);
            view.setMessage("取消点赞成功");
            this.circleUpService.delete(circleUp.getId());
        }
        CircleQuery cq = this.circleService.getCircleDetail(circle);
        view.setData(cq);
        return view;
    }

}
